import React, { PureComponent } from 'react'
import { connect } from 'react-redux'
import {
  addNumberAction,
  subNumberAction,
} from '../store/counter/actionCreators'

export class About extends PureComponent {
  render() {
    const { counter, banners, recommends, userInfo } = this.props

    return (
      <div>
        <div className="userInfo">
          <h2>nickname: {userInfo.nickname}</h2>
        </div>
        <h2>about counter: {counter}</h2>
        <div>
          <button onClick={(e) => this.calcNumber(6, true)}>+6</button>
          <button onClick={(e) => this.calcNumber(6, false)}>-6</button>
          <button onClick={(e) => this.calcNumber(8, true)}>+8</button>
          <button onClick={(e) => this.calcNumber(8, false)}>-8</button>
        </div>

        <div className="banner">
          <h2>轮播图数据</h2>
          <ul>
            {banners.map((item, index) => (
              <li key={index}>{item.title}</li>
            ))}
          </ul>
        </div>

        <div className="recommend">
          <h2>推荐数据</h2>
          <ul>
            {recommends.map((item, index) => (
              <li key={index}>{item.title}</li>
            ))}
          </ul>
        </div>
      </div>
    )
  }

  calcNumber(num, isAdd) {
    if (isAdd) {
      this.props.addNumber(num)
    } else {
      this.props.subNumber(num)
    }
  }
}

// connect()返回值时一个高阶组件
function mapStateToProps(state) {
  return {
    counter: state.counter.counter,
    banners: state.home.banners,
    recommends: state.home.recommends,
    userInfo: state.user.userInfo,
  }
}

function mapDispatchToProps(dispatch) {
  return {
    addNumber(num) {
      dispatch(addNumberAction(num))
    },
    subNumber(num) {
      dispatch(subNumberAction(num))
    },
  }
}
export default connect(mapStateToProps, mapDispatchToProps)(About)
